/**
 * Background main for handling tab events
 *
 * Establish communication between content script and extension script
 * Communication packet
 * - checkoutData:
 * 		+ ticketId: Service Now Change Request ID
 * 		+ files: list of file names using absolute path
 * - cmoData - ticket:
 * 		+ type: {ticket.init.request | file.checkin.complete|file.checkout.complete|ticket.sync.complete
 * 					| ticket.init.response | file.checkin.started | file.checkout.started | ticket.sync.started}
 * 		+ payload: checkoutData
 * - cmoData - copy:
 * 		+ type: clipboard.copy
 * 		+ payload: string
 */
//chrome.extension.onConnect.addListener(function(port) {
//	console.assert(port.name == "cmo");
//	console.log('Content scripting connected');
//	
//	port.onMessage.addListener(function(cmoData) {
//		console.log('Content says: ');
//		console.log(cmoData);
//		if (cmoData.type = 'ticket.init.request') {
//			cmoData.type = 'ticket.init.response';
//			cmoData.payload = {ticket:'CHG0012345', files:['/file1', '/file2']};
//			port.postMessage(cmoData);
//		}		
//	    
//	    console.log('Sent data back to content');
//	});
//});

function generateContextMenu() {
	var contexts = ["selection"];
	// Create the CMO Tools root
	var parent = chrome.contextMenus.create({
				"id":"mnu-cmo",
				"title": "CMO Tools",
				"contexts":contexts
			});
	// Create the Check out command item
	chrome.contextMenus.create({
				"id":"mnu-cmo-checkout",
				"title": "Check out",
				"parentId":parent,
				"contexts":contexts
			});
	/** 
	 * OnClickData info
	 * tabs.Tab tab
	 */ 
	chrome.contextMenus.onClicked.addListener(function(info, tab) {
		console.log('Selection: ' + info.selectionText);
		var files = info.selectionText.split(/\r\n|\r|\n|\s/);
		chrome.tabs.sendMessage(tab.id, {type: 'file.checkout',files:files}, function(response) {
			console.log(response);
		});
	});
}

function normalizeFilename(filename) {
	return filename.replace('/home/webuser/site/','');
}

generateContextMenu();